package com.virtualtrainer_01.dao;

import java.util.HashMap;

import com.virtualtrainer_01.model.Model;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public abstract class SQLiteDB {
	protected static final String DATABASE_NAME = "virtualTDb";
	protected static final int DATABASE_VERSION = 1;
	private DbHelper ourHelper;
	protected final Context ourContext;
	protected SQLiteDatabase ourDatabase;
	private String tableName;

	protected class DbHelper extends SQLiteOpenHelper {
		String table = "";

		public DbHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {			
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			String sql = "DROP TABLE IF EXISTS " + table;
			db.execSQL(sql);
			onCreate(db);
		}
	}

	public SQLiteDB(Context c, String tableName) {
		this.tableName = tableName;
		ourContext = c;
	}
	
	public SQLiteDB open() throws SQLException {		
		this.ourHelper = new DbHelper(ourContext);
		this.ourDatabase = ourHelper.getWritableDatabase();		
		return this;
	}
	
	public SQLiteDB commit(String sql) throws SQLException{
	
		try {
			ourDatabase.execSQL(sql);
		} catch (SQLiteException e) {			
			e.printStackTrace();
		}
		return this;
	}
	
	public void close() {
		ourHelper.close();
	}
	
	public abstract long createEntry(Model entry); 
	
	public abstract String getData() ;
	
	public void insert(HashMap<String, Object> entryList)
	{
		String sql = "INSERT INTO '"+tableName+ "' (";
		for(String key : entryList.keySet())
			sql+="'"+key+"',";
		sql = sql.substring(0, sql.length()-1);
		sql+=") VALUES (";
		for(Object value : entryList.values())
			sql += "'"+value+"',";
		sql = sql.substring(0, sql.length()-1);
		sql+=")";		
		commit(sql);
	}
	
	public int getId(Model entry)
	{	
		int id = -1;
		String sql = "SELECT t._id FROM "+tableName+" t where t.name="+"'"+entry.getName()+"';";
		Cursor c = ourDatabase.rawQuery(sql, null); 
		for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
			id = c.getInt(c.getColumnIndex("_id"));
		return id;
	}
	
	public int getId(String name)
	{
		String sql = "SELECT t._id FROM "+tableName+" t where t.name="+"'"+name+"';";
		Cursor c = ourDatabase.rawQuery(sql, null); 
		
		int iRow = c.getColumnIndex("_id");	
		int id = -1;
		for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())		
			id = Integer.parseInt(c.getString(iRow));				
		return id;
	}
}
